import json, base64
import hmac, hashlib

header = {
    'typ': 'JWT',
    'alg': 'HS256'
}

header = json.dumps((header))
header = base64.b64encode(header.encode())
print(header)

payload = {
    'sub': '1234567890',
    'name': 'John Doe',
    'admin': True,
    'age': 20
}

payload = json.dumps(payload)
payload = base64.b64encode(payload.encode())
print(payload)

msg = header + b'.' + payload
SECRET_KEY = b'gt8q%+_wpt5a@(ps3nwn35%wd4tqp@y4+o8n!t-(*s*_%h=a-5'

hash_obj = hmac.new(SECRET_KEY, msg=msg, digestmod=hashlib.sha256)
signature = hash_obj.hexdigest()
print(signature)

JWT_TOKEN = header.decode() + '.' + payload.decode() + '.' + signature
print(JWT_TOKEN)

jwt_token_from_browser = JWT_TOKEN
# jwt_token_from_browser = 'fff' + JWT_TOKEN

header = jwt_token_from_browser.split('.')[0]
payload = jwt_token_from_browser.split('.')[1]
signature = jwt_token_from_browser.split('.')[2]

msg = header + '.' + payload
new_signature = hmac.new(SECRET_KEY, msg.encode(), digestmod=hashlib.sha256).hexdigest()

# if new_signature == signature:
if hmac.compare_digest(new_signature, signature):
    print("数据完整")
    payload = base64.b64decode(payload)
    payload = json.loads(payload.decode())
    print(payload)
else:
    print("数据被篡改了")